import parseAttrsString from './parseAttrsString'
export default function parse(templateStr) {
  let index = 0
  let rest = ""
  let startRegExp = /^\<([a-z]+[1-6]?)(\s[^\<]+)?\>/
  let endRegExp = /^\<\/([a-z]+[1-6]?)\>/
  let wordRegExp = /^([^\<]+)\<\/([a-z]+[1-6]?)\>/
  let stack1 = []
  let stack2 = [{tag:'我是用来存储最后的AST的',children:[]}]
  while (index < templateStr.length) {
    rest = templateStr.substring(index)
    // 匹配开始标签
    if (startRegExp.test(rest)) {
      let tag = rest.match(startRegExp)[1]
      let attrsString = rest.match(startRegExp)[2]
      let attrsArr=parseAttrsString(attrsString)
      // console.log(tag + "进栈")
      stack1.push(tag)
      // console.log("当前的stack1:",stack1)
      stack2.push({tag:tag,children:[], attrs:attrsArr})
      // console.log("当前的stack2:",JSON.stringify(stack2))
      index = index + tag.length + 2
    } else if (endRegExp.test(rest)) {
      let tag = rest.match(endRegExp)[1]
      let pop_tag=stack1.pop()
      // console.log(tag + "出栈")
      // console.log("当前的stack1:", stack1)
      if (tag == pop_tag) {
        let tagObj = stack2.pop()
      stack2.length > 0 && stack2[stack2.length - 1].children.push(tagObj)
      // console.log("当前的stack2:", JSON.stringify(stack2))
      } else {
        throw new Error(`${tag}标签没有闭合`)
      }
      index = index + tag.length + 3
    } else if (wordRegExp.test(rest)) {
      let tag = rest.match(wordRegExp)[1]
      if (!/^\s+$/.test(tag)) {
      // console.log("匹配的文字:", tag)
      stack2[stack2.length - 1].children.push({ text: tag, type: 3 })
      // console.log("当前的stack2:",JSON.stringify(stack2))
      }
      index += tag.length
    } else {
      index++
    }
  }
  console.log("AST", stack2[0].children[0])
  return stack2[0].children[0]
}
